import { EChartOption } from 'echarts'
import { EChartsBase } from '@/facade/echarts'
import convert from '@/utils/convert'

const green = require('@/assets/image/green.png')
const green2 = require('@/assets/image/green2.png')
const yellow = require('@/assets/image/yellow.png')
const yellow2 = require('@/assets/image/yellow2.png')
const doubleYellow = require('@/assets/image/doubleYellow.png')
const doubleYellow2 = require('@/assets/image/doubleYellow2.png')
const redYellow = require('@/assets/image/redYellow.png')
const redYellow2 = require('@/assets/image/redYellow2.png')
const red = require('@/assets/image/red.png')
const red2 = require('@/assets/image/red2.png')
const white = require('@/assets/image/white.png')
const white2 = require('@/assets/image/white2.png')
const greenYellow = require('@/assets/image/greenYellow.png')
const greenYellow2 = require('@/assets/image/greenYellow2.png')
const yellowTwo = require('@/assets/image/yellowTwo.png')
const yellowTwo2 = require('@/assets/image/yellowTwo2.png')

const LightObj = {
  '1': green,
  '1-2': green2,
  '2': yellow,
  '2-2': yellow2,
  '3': doubleYellow,
  '3-2': doubleYellow2,
  '4': redYellow,
  '4-2': redYellow2,
  '5': red,
  '5-2': red2,
  '6': white,
  '6-2': white2,
  '7': greenYellow,
  '7-2': greenYellow2,
  '8': yellowTwo,
  '8-2': yellowTwo2
}

const PhaseIcon = {
  '开车事件': require('@/assets/image/kaicheshijian.png'),
  '停车事件': require('@/assets/image/tingcheshijian.png'),
  '监控动作（事件）': require('@/assets/image/jiankongdongzuo.png'),
  '侧线运行（事件）': require('@/assets/image/cexianyunxing.png'),
  '人为紧急（事件）': require('@/assets/image/renweijinji.png'),
  '进入调车（事件）': require('@/assets/image/jinrudiaoche.png'),
  '退出调车（事件）': require('@/assets/image/tuichudiaoche.png'),
  '过分相点（事件）': require('@/assets/image/guofenxiangdian.png'),
  '特殊区域（事件）': require('@/assets/image/teshuquyu.png'),
  '调车开行（事件）': require('@/assets/image/diaochekaixing.png'),
  '红黄信号': require('@/assets/image/honghuangxinhao.png'),
  '开关视频（事件）': require('@/assets/image/kaiguanshipin.png'),
  '内燃停机（事件）': require('@/assets/image/neirantingji.png'),
  '继乘交接（事件）': require('@/assets/image/jichengjiaojie.png'),
  '总风低压（事件）': require('@/assets/image/zongfengdiya.png'),
  '机器间报警（事件）': require('@/assets/image/jiqijianbaojing.png'),
  '电器间报警（事件）': require('@/assets/image/dianqijianbaojing.png'),
  '黄灯信号（事件）': require('@/assets/image/huangdengxinhao.png'),
  '乘务巡检': require('@/assets/image/chengwuxunjian.png'),
  '减压制动': require('@/assets/image/jianyazhidong.png'),
  '特殊通行': require('@/assets/image/teshutongxing.png'),
  '打盹报警（事件）': require('@/assets/image/dadunbaojing.png'),
  '轨道异常（事件）': require('@/assets/image/guidaoyichang.png')
}

const colorObj = {
  绿: 'green',
  2: 'yellow',
  黄: 'yellow',
  双: 'yellow',
  红: 'red',
  白: 'white'
}

const cabSignalMap = {
  '0': '无灯',
  '1': '绿',
  '2': '黄',
  '3': '双黄',
  '4': '红黄',
  '5': '红',
  '6': '白',
  '7': '绿黄',
  '8': '黄2'
}

const colors = ['#00EE00', '#F07000', '#ff0000']

export default class IdxChart extends EChartsBase {
  // constructor(){
  //   this._list= []
  //   this. _index = 0
  //   this. _xNumber = 30
  //   this._limitSpeeds = []
  //   this._phases = []
  //   this._xType = '时间'
  //   this._idx = {}
  // }
  // 获取宽度
  get width() {
    return super.width - 90
  }

  // 获取长度
  get height() {
    return super.height * 0.9
  }

  // 获取从属列表
  get list() {
    return this._list
  }
  set list(value) {
    this._list = value
  }

  // 从属项点
  get phases() {
    return this._phases
  }
  set phases(value) {
    this._phases = value
  }

  // 从属限速
  get limitSpeeds() {
    return this._limitSpeeds
  }
  set limitSpeeds(value) {
    this._limitSpeeds = value
  }

  // 从属idx主记录
  get idx() {
    return this._idx
  }
  set idx(value) {
    this._idx = value
  }

  // 从属列表当前索引值
  get index() {
    return this._index
  }
  set index(value) {
    this._index = value
    this.setOption(this.chartOption)
  }

  // x轴
  get xNumber() {
    return this._xNumber
  }
  set xNumber(value) {
    this._xNumber = value
  }

  // x轴显示类型
  get xType() {
    return this._xType
  }
  set xType(value) {
    this._xType = value
    this.setOption(this.chartOption)
  }

  // 初始化配置信息
  get initOptions() {
    return {
      color: colors,
      tooltip: {
        backgroundColor: '#fff',
        borderColor: '#ddd',
        borderWidth: 1,
        trigger: 'axis',
        textStyle: {
          color: '#3c3c3c',
          fontSize: 16
        },
        label: {
          color: 'black'
        },
        axisPointer: {
          type: 'cross'
        },
        padding: 10,
        formatter(params) {
          let str = ''
          let name = ''
          for (let i = 0; i < params.length; i += 1) {
            if (params[i].data.cabSignal) {
              str += `<div style="height:8px;width:8px;border-radius:50%;background:black;float:left;margin-top:8px;margin-right:5px;"></div>信号灯：${
                params[i].data.cabSignal
              }灯 <br>`
            } else if (params[i].type === 'bar' || params[i].type === 'pictorialBar') {
              str += ''
            } else {
              name = `${params[i].name}<br>`
              str += `<div style="height:8px;width:8px;border-radius:50%;background:${
                params[i].color
              };float:left;margin-top:8px;margin-right:5px;"></div>${params[i].seriesName}：${
                params[i].data
              } <br>`
            }
          }
          return `${name}${str}`
        }
      },
      grid: {
        top: '17%',
        left: 45,
        right: 45,
        bottom: 23
      },
      legend: {
        data: [
          {
            name: '速度km/h',
            icon: 'circle'
          },
          {
            name: '管压kPA',
            icon: 'circle'
          },
          {
            name: '限速',
            icon: 'circle'
          }
        ],
        textStyle: {
          color: '#FFFFFF'
        }
      },
      xAxis: [
        {
          type: 'category',
          axisTick: {
            alignWithLabel: true
          },
          interval: 1,
          axisLine: {
            lineStyle: {
              color: '#FFFFFF',
              width: 1,
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#FFFFFF'
          },
          axisPointer: {
            label: {
              color: 'black'
            }
          },
          data: [],
          boundaryGap: false
        },
        {
          show: false,
          type: 'category',
          gridIndex: 0,
          axisTick: {
            alignWithLabel: true
          },
          interval: 1,
          axisLine: {
            lineStyle: {
              color: '#FFFFFF',
              width: 1,
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#FFFFFF',
            interval: 4
          },
          axisPointer: {
            show: false
          },
          data: []
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '速度km/h',
          min: 0,
          max: 160,
          position: 'right',
          axisLine: {
            lineStyle: {
              color: colors[0]
            }
          },
          splitLine: { show: false }
        },
        {
          type: 'value',
          name: '管压kPA',
          min: 0,
          max: 700,
          position: 'left',
          axisLine: {
            lineStyle: {
              color: colors[1]
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        {
          show: false,
          type: 'value',
          name: '限速',
          min: 0,
          max: 160,
          position: 'right',
          offset: 80,
          axisLine: {
            lineStyle: {
              color: colors[2]
            }
          },
          axisPointer: {
            show: false
          }
        },
        {
          show: false,
          type: 'value',
          min: 0,
          max: 160,
          name: '信号灯'
        }
      ],
      series: [
        {
          name: '速度km/h',
          type: 'line',
          data: [],
          showSymbol: false,
          hoverAnimation: false,
          animation: false
        },
        {
          name: '管压kPA',
          type: 'line',
          yAxisIndex: 1,
          showSymbol: false,
          hoverAnimation: false,
          data: [],
          animation: false
        },
        {
          name: '限速',
          type: 'line',
          yAxisIndex: 2,
          showSymbol: false,
          data: [],
          hoverAnimation: false,
          animation: false
        },
        {
          name: '信号灯',
          type: 'pictorialBar',
          data: [],
          xAxisIndex: 0,
          yAxisIndex: 3,
          Signal: true,
          symbolSize: [8, 18],
          symbolOffset: [2, -10],
          zlevel: 999,
          lineStyle: {
            opacity: 0
          },
          animation: false
        },
        {
          stack: '信号量',
          type: 'bar',
          xAxisIndex: 1,
          barCategoryGap: '0%',
          seriesLayoutBy: 'row',
          data: [],
          label: {
            normal: {
              show: false,
              position: 'insideRight'
            }
          },
          animation: false
        },
        {
          stack: '信号量',
          xAxisIndex: 1,
          type: 'bar',
          barCategoryGap: '0%',
          seriesLayoutBy: 'row',
          data: [],
          label: {
            normal: {
              show: false,
              position: 'insideRight'
            }
          },
          animation: false
        },
        {
          name: '项点标记',
          type: 'pictorialBar',
          data: [],
          xAxisIndex: 1,
          yAxisIndex: 3,
          symbolSize: [18, 18],
          symbolOffset: [0, -50],
          zlevel: 9,
          animation: false
        }
      ]
    }
  }

  get chartOption() {
    const xAxis = [
      { data: [] }
    ]
    const series  = [
      { data: [] }, // 速度
      { data: [] }, // 管压
      { data: [] }, // 限速
      { data: [] }, // 信号灯
      { data: [] }, // 信号量1
      { data: [] }, // 信号量2
      { data: [] } // 项点标记
    ]

    if (this.list && this.list.length > 0) {
      for (let i = 0; i <= this.xNumber; i++) {
        const index = this.index + i
        const current = this.list[index]
        const prev = this.list[index - 1] || {}
        const next = this.list[index + 1] || {}
        const goodsNum = (current.goodsNum || '').split('-') || []
        const timez = convert.dateFormat(new Date(current.platformTime), 'HH:mm:ss')
        const cabSignal = cabSignalMap[(current.cabSignal || [])[1] || '0'].replace(/['灯', '闪']/g, '') || '无'
        let showSymbol = false
        let colorNum = ''
        const signalNumber = current.signalNum
        const signParams = {
          value: 0,
          symbol: '-',
          showSymbol,
          cabSignal
        }
        // 判断是否显示信号机
        if (next.cabSignal && `${current.signalType}-${current.signalNum}` !== `${next.signalType}-${next.signalNum}`) {
          showSymbol = true
          // 若是进站，则需要显示两个灯，否则只显示一个灯
          if (current.signalType === '3') {
            colorNum = '-2'
          } else {
            colorNum = ''
          }
          Object.assign(signParams, {
            value: 140,
            symbol: `image://${LightObj[`${current.cabSignal[1]}${colorNum}`]}`,
            label: {
              show: showSymbol,
              position: 'bottom',
              formatter: signalNumber,
              color: '#fff',
              fontSize: 9,
              offset: [12, -23]
            }
          })
        }
        if (!current.isHandled) {
          current.timez = timez
          current.ke = goodsNum[0]
          current.ben = goodsNum[1]
          current.iscar = current.deviceStatus === '0-0' ? '开车' : ''
          current.checi = this.idx.trainNum
          current.riqi = this.idx.date
          current.jichehao = this.idx.cabNum
          current.handleLevel = (current.handleLevel * 0.1).toFixed(1)
          current.meterLengh = (current.meterLengh * 0.1).toFixed(1)
          current.kilometre = (current.kilometre * 0.001).toFixed(3)
          current.cabSignalText = cabSignal
          current.isHandled = true // 已处理标志
        }

        xAxis.map((x, index) => {
          switch (index) {
            case 0: // 公里标
              if (this._xType === '时间') {
                x.data.push(current.timez)
              } else {
                x.data.push(current.kilometre)
              }
              break
            default:
              x.data.push(0)
              break
          }
        })

        let mineColor1 = '#333333'
        let mineColor2 = '#333333'
        if (cabSignal === '无') {
          mineColor1 = '#333333'
          mineColor2 = '#333333'
        } else if (cabSignal.length === 2) {
          mineColor1 = colorObj[cabSignal[0]]
          mineColor2 = colorObj[cabSignal[1]]
        } else if (cabSignal.length === 1) {
          mineColor1 = colorObj[cabSignal]
          mineColor2 = colorObj[cabSignal]
        }

        let phase = {}
        let showPhaseSymbol = false
        if (current.platformTime) {
          const platformTime = new Date(current.platformTime).getTime()
          if (this._limitSpeeds && this._limitSpeeds.length > 0) {
            const index = this._limitSpeeds.findIndex((a) => a.time > platformTime)
            let obj = {}
            if (index - 1 >= 0) {
              obj = this._limitSpeeds[index - 1]
            } else {
              obj = this._limitSpeeds[0]
            }
            Object.assign(current, {
              rateLimit: obj.limit
            })
          }

          if (this._phases && this._phases.length > 0) {
            const phases = this._phases.filter((a) => a.startTime <= platformTime && a.endTime > platformTime)
            phase = phases.reduce((result, item) => {
              if (!result.id || result.startTime < item.startTime) return item
              return result
            }, {})
            if (phase && phase.id) {
              Object.assign(current, {
                phaseId: phase.id
              })
            }
            showPhaseSymbol = !!phase && prev.phaseId !== phase.id
          }
        }
        series.map((s, index) => {
          switch (index) {
            case 0: // 速度
              s.data.push(current.speed)
              break
            case 1: // 管压
              s.data.push(current.trainPipePressure)
              break
            case 2: // 限速
              s.data.push(current.rateLimit)
              break
            case 3: // 信号灯
              s.data.push(signParams)
              break
            case 4: // 信号量1
              s.data.push({
                value: 6,
                itemStyle: {
                  normal: {
                    color: mineColor1
                  }
                }
              })
              break
            case 5: // 信号量2
              s.data.push({
                value: 5,
                itemStyle: {
                  normal: {
                    color: mineColor2
                  }
                }
              })
              break
            case 6: // 项点标记
              s.data.push({
                value: 45,
                symbol: `image://${PhaseIcon[showPhaseSymbol ? phase.name : '-']}`
              })
              break
            default:
              break
          }
        })
      }
    }
    const result = {
      xAxis,
      series
    }
    return result
  }

  // 构造函数
  constructor($el, list, index, limitSpeeds, phases, click, xType, xNumber) {
    super($el)
    this._list = list
    this._xNumber = 30
    this._index = index
    this._limitSpeeds = limitSpeeds
    this._phases = phases
    this._xNumber = xNumber || this._xNumber
    this._xType = xType || '时间'
    this.setOption(this.initOptions)
    this.click = (value) => {
      click(this.index + value)
    }
  }
}
